package com.example.blog.modules.user.controller;

import com.example.blog.common.api.ApiResponse;
import com.example.blog.common.service.FileStorageService;
import com.example.blog.modules.user.dto.UserDTO;
import com.example.blog.modules.user.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@Tag(name = "用户接口", description = "用户信息管理相关接口")
@RestController
@RequestMapping("/api/users")
@RequiredArgsConstructor
@SecurityRequirement(name = "bearerAuth")
public class UserController {
    
    private final UserService userService;
    private final FileStorageService fileStorageService;
    
    @Operation(summary = "获取当前用户信息")
    @GetMapping("/me")
    public ApiResponse<UserDTO> getCurrentUser() {
        return ApiResponse.success(userService.getCurrentUser());
    }
    
    @Operation(summary = "获取指定用户信息")
    @GetMapping("/{id}")
    public ApiResponse<UserDTO> getUser(@PathVariable Long id) {
        return ApiResponse.success(userService.getUserById(id));
    }
    
    @Operation(summary = "更新用户信息")
    @PutMapping("/{id}")
    @PreAuthorize("@securityService.isCurrentUser(#id)")
    public ApiResponse<UserDTO> updateUser(@PathVariable Long id, @RequestBody UserDTO userDTO) {
        return ApiResponse.success(userService.updateUser(id, userDTO));
    }
    
    @Operation(summary = "上传用户头像")
    @PostMapping("/{id}/avatar")
    public ApiResponse<UserDTO> uploadAvatar(@PathVariable Long id, @RequestParam("file") MultipartFile file) {
        String avatarUrl = fileStorageService.store(file, "avatars");
        
        UserDTO userDTO = new UserDTO();
        userDTO.setAvatar(avatarUrl);
        
        return ApiResponse.success(userService.updateUser(id, userDTO));
    }
    
    @Operation(summary = "删除用户")
    @DeleteMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public ApiResponse<Void> deleteUser(@PathVariable Long id) {
        userService.deleteUser(id);
        return ApiResponse.success();
    }
} 